/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package simple;

import algorithm.MultiOperator;
import algorithm.Individual;
/**
 *
 * @author Pierre
 */
public class CrossOverOperator implements MultiOperator {

    public Individual[] operate(Individual[] individuals) throws Exception {
        if (individuals.length != 2) {
            throw new IncorrectConfigException("This operator requires exactly two inputs");
        }
        if (individuals[0].getGenotype() instanceof BitStringGenotype
                && individuals[1].getGenotype() instanceof BitStringGenotype) {
            short[] gen1 = ((BitStringGenotype) individuals[0].getGenotype()).getBits();
            short[] gen2 = ((BitStringGenotype) individuals[1].getGenotype()).getBits();
            if (gen1.length != gen2.length) {
                throw new UnimplementedException("Currently bitstring operator requires equal length bitstrings.");
            }
            int pos1 = (int) (Math.random() * gen1.length);
            // make sure we actually fo cross somewhere in the string,
            // instead of completely exchaning dna
            if (pos1==0) {
                pos1 = 1;
            }
            short[] ret1 = new short[gen1.length];
            short[] ret2 = new short[gen2.length];
            for (int i=0;i<pos1;++i) {
                ret1[i] = gen1[i];
                ret2[i] = gen2[i];
            }
            for (int i=pos1;i<gen1.length;++i) {
                short tmp = gen1[i];
                ret1[i] = gen2[i];
                ret2[i] = tmp;
            }
            Individual[] returnIndividuals = new Individual[2];
            returnIndividuals[0] = Factory.createIndividual(individuals[0].getClass(),new BitStringGenotype(ret1));
            returnIndividuals[1] = Factory.createIndividual(individuals[1].getClass(),new BitStringGenotype(ret2));
            return returnIndividuals;
            
        } else {
            throw new IncorrectConfigException("Only implemented for BitString Genotypes");
        }
    }
}
